#include "cmsisDapUSB.h"

#include <cmsisDAP/cmsisDapHid.h>

cmsisDapUSB::cmsisDapUSB()
{

}

cmsisDapUSB::~cmsisDapUSB()
{
    close();
}

bool cmsisDapUSB::open(const char *dev, long params)
{
    cmsisDapHid *hid;
    int ret;

    if (!cmsisDAP::init())
        return false;

    hid = new cmsisDapHid;
    ret = hid->open(dev);
    if (ret != 0)
    {
        cmsisDAP::deinit();
        delete hid;
        return false;
    }

    hid->packet_buffer_alloc(&_dap, 64);

    _dap.backend = hid;

    return true;
}

void cmsisDapUSB::close()
{
    if (_dap.backend)
    {
        _dap.backend->close();
        _dap.backend = nullptr;
    }
}

int cmsisDapUSB::dap_read(struct cmsis_dap *dap, int timeout_ms)
{
    if (!dap->backend)
        return -1;

    return dap->backend->read(dap, timeout_ms);
}

int cmsisDapUSB::dap_write(struct cmsis_dap *dap, int len, int timeout_ms)
{
    if (!dap->backend)
        return -1;

    return dap->backend->write(dap, len, timeout_ms);
}
